package com.aliyun.frontserver;

import com.aliyun.frontframework.NewFrontCamera;

import android.R;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.view.Surface;

public class CoreService extends Service {

    NewFrontCamera mNewFrontCamera;

    public void drawFrame() {
        mNewFrontCamera.drawFrame();
    }

    private void openCamera() {
        int desiredWidth = 1920;
        int desiredHeight = 1088;
        int desiredFps = 15;
        mNewFrontCamera.openCamera(desiredWidth, desiredHeight, desiredFps);
    }

    private void releaseCamera() {
        mNewFrontCamera.releaseCamera();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null || intent.getExtras() == null) {
            return super.onStartCommand(intent, flags, startId);
        }
        Log.d("Core", "onStartCommand "+intent);
        Log.d("Core", "onStartCommand");
        String behavior = intent.getStringExtra("behavior");
        if ("startRecord".equals(behavior)) {
            mNewFrontCamera.startRecord();
        } else if ("stopRecord".equals(behavior)) {
            mNewFrontCamera.stopRecord();
        } else if ("openCamera".equals(behavior)) {
            openCamera();
        } else if ("releaseCamera".equals(behavior)) {
            releaseCamera();
        } else if ("surfaceAction".equals(behavior)) {
            Surface surface = intent.getParcelableExtra("surface");
            int width = intent.getIntExtra("width", 1);
            int height = intent.getIntExtra("height", 1);
            String action = intent.getStringExtra("action");
            String code = intent.getStringExtra("code");
            Log.d("Core", "width " + width);
            Log.d("Core", "height " + height);
            Log.d("Core", "action " + action);
            if ("surfaceCreated".equals(action)) {
                mNewFrontCamera.setDisplaySurface(surface, width, height, code);
            } else if ("surfaceChanged".equals(action)) {
                mNewFrontCamera.setDisplaySurface(surface, width, height, code);
            } else if ("surfaceDestroyed".equals(action)) {
                mNewFrontCamera.setDisplaySurface(surface, code);
            }
        }
 
        // 传递surface
        boolean isSurfaceIntent = intent
                .getBooleanExtra("surfaceIntent", false);
        if (isSurfaceIntent) {
            
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mNewFrontCamera = new NewFrontCamera(CoreService.this);
        Log.d("Core", "onCreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }
}
